<template>
    <div class="minW1060-auto bg-fff mt10">
        <div class="pad20 ml10">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/area' }">区域管理</el-breadcrumb-item>
                <el-breadcrumb-item>区域添加</el-breadcrumb-item>
            </el-breadcrumb>

            <el-row>
                <el-col align="right">
                    <div class="dlblock-mb20 pr10 ml20">
                        <el-button type="primary" @click="areaSave()">保存</el-button>
                    </div>
                </el-col>
            </el-row>

            <el-row>
                <el-col align="left">
                    <h1>基本信息</h1>
                </el-col>
            </el-row>

            <el-row :gutter="30" class="mt20">

                <el-form label-position="left" :rules="rules" label-width="100px" ref="groups">

                    <el-row>
                        <el-col :span="6" :offset="1">
                            <el-form-item label="所属分组">
                                <el-cascader
                                        v-model="areaGroups"
                                        :options="groups"
                                        :show-all-levels="false"
                                        :props="{value: 'id', label: 'name',  checkStrictly: true,expandTrigger: 'hover' }"
                                        style="width: 280px"
                                        clearable>
                                </el-cascader>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6" :offset="1">
                            <el-form-item label="区域类型">
                                <el-select v-model="area.type " clearable class="size-full">
                                    <el-option label="未设置" :value="0"></el-option>
                                    <el-option label="限速区域" :value="1"></el-option>
                                    <el-option label="停车场" :value="2"></el-option>
                                    <el-option label="加油站充电区" :value="3"></el-option>
                                    <el-option label="告警区域" :value="4"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6" :offset="1">
                            <el-form-item label="区域名称">
                                <el-input v-model="area.name"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" :offset="1">
                            <el-form-item label="名称拼音">
                                <el-input readonly="readonly" v-model="pinyin"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6" :offset="1">
                            <el-form-item label="拼音缩写">
                                <el-input readonly="readonly" v-model="abbr"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" :offset="1">
                            <el-form-item v-if="area.type==1" label=" 最高时速">
                                <el-input v-model="area.value" type="text" placeholder="最高时速"/>
                            </el-form-item>
                            <el-form-item v-else-if="area.type==2" label=" 可停车辆数">
                                <el-input v-model="area.value" type="text"
                                          placeholder="可停车辆数"/>
                            </el-form-item>
                            <el-form-item v-else-if="area.type!=1&&area.type!=2" label=" 动态设定值">
                                <el-input placeholder="无动态设定值" type="text"
                                          readonly="readonly"/>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="6" :offset="1">
                            <el-form-item label="禁用状态">
                                <el-radio-group v-model="disabled">
                                    <el-radio :label="1">已禁用</el-radio>
                                    <el-radio :label="0">未禁用</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" :offset="1">
                            <el-form-item label="隐藏状态">
                                <el-radio-group v-model="hidden">
                                    <el-radio :label="1">已隐藏</el-radio>
                                    <el-radio :label="0">未隐藏</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>

                </el-form>
            </el-row>

            <el-row>
                <el-col align="left">
                    <h1 @click="reset()">绘制区域</h1>
                </el-col>

            </el-row>
            <br/>

            <el-button type="text" @click="dialogVisible2()">点击开始绘制</el-button>

            <div class="map">
                <el-dialog
                        :visible.sync="dialogVisible"
                        width="60%"
                        height="30%"
                        :show-close="false"
                        :destroy-on-close="true"
                        :before-close="handleClose">

                    <div class="dlblock-mb20 pr10">
                        <el-button type="danger" @click="clearAll()">清除所有区域</el-button>
                    </div>

                  <span slot="footer" class="dialog-footer">
                     <div id="dbmap"></div>
                    <br/>
                     <el-button @click="cancel()">取 消</el-button>
                     <el-button type="primary" @click="save()">保 存</el-button>
             </span>
                </el-dialog>

                <template>
                    <img class="img" :src="url"/>
                </template>

            </div>
        </div>
    </div>
</template>

<script>

//引入汉字转拼音插件文件
import vPinyin from '../../../../utils/vue-py'
import {getGroupTree, saveArea} from '@/api';

export default {
  name: 'index1',
  data() {
    return {
      //对话框
      dialogVisible: false,

      area: {
        type: '',
      },

      //分组信息
      areaGroups: '',
      groups: [],

      //  验证规则
      rules: {},

      //百度地图
      path: '',
      pts: [],
      map: null,
      drawingManager: null,

      //cancel 取消用的集合
      ptsCancel: [],

      overlays: [],

      //拼音首字母
      pinyin: '',
      abbr: '',

      //是否隐藏
      disabled: '',
      hidden: '',

      //图片URL
      url: '',

      //中心点
      longitude: '',
      latitude: '',
      zoom: ''

    }
        },

        watch: {

            'area.name': {
                handler(newValue, oldValue) {

                    this.pinyin = vPinyin.chineseToPinYin(this.area.name)

                    let SX = '';
                    for (var i = 0; i < this.pinyin.length; i++) {
                        var c = this.pinyin.charAt(i);
                        if (/^[A-Z]+$/.test(c)) {
                            SX += c;
                        }
                    }
                    this.abbr = SX;

                }

            },

            dialogVisible: function () {

                if (this.dialogVisible == false) {
                    if (this.pts != null && this.pts.length == 0) {
                        this.url = ""
                    }
                    else if (this.pts != null && this.pts.length > 0) {
                        this.area.pts = this.pts

                        if (this.area.pts != undefined && this.area.shape == 3) {

                            this.longitude = (this.area.pts[0])
                            this.latitude = (this.area.pts[1])

                            let maxLng = this.area.pts[2];
                            let minLng = this.area.pts[2];
                            for (let i = 2; i < this.area.pts.length; i += 2) {
                                let cut = this.area.pts[i];
                                cut > maxLng ? maxLng = cut : null;
                                cut < minLng ? minLng = cut : null;
                            }

                            let maxLat = this.area.pts[3];
                            let minLat = this.area.pts[3];
                            for (let i = 3; i < this.area.pts.length; i += 2) {
                                let cur = this.area.pts[i];
                                cur > maxLat ? maxLat = cur : null;
                                cur < minLat ? minLat = cur : null;
                            }

                            this.zoom = this.getZoom(maxLng, minLng, maxLat, minLat);

                            let pathPolygon = ''
                            for (let i = 2; i < this.area.pts.length; i += 2) {
                                pathPolygon = pathPolygon + parseFloat(this.area.pts[i]) + ',' + parseFloat(this.area.pts[i + 1]) + ';'
                            }

                            this.url = `http://api.map.baidu.com/staticimage/v2?ak=0MA953dkYQM4fQriWe6NaII8QpjeCCZh&center=${ this.longitude},${ this.latitude}&width=1000&height=320&zoom=${this.zoom+1}&paths=${pathPolygon}&pathStyles=0xff0000,5,0.9,0xffffff&bbox=500,500;500,500 `
                        } else if (this.area.pts != undefined && this.area.shape == 1) {

                            var maxLng = this.area.pts[0];
                            var minLng = this.area.pts[0];
                            for (let i = 0; i < this.area.pts.length; i += 2) {
                                var cut = this.area.pts[i];
                                cut > maxLng ? maxLng = cut : null;
                                cut < minLng ? minLng = cut : null;
                            }

                            var maxLat = this.area.pts[1];
                            var minLat = this.area.pts[1];
                            for (let i = 1; i < this.area.pts.length; i += 2) {
                                var cur = this.area.pts[i];
                                cur > maxLat ? maxLat = cur : null;
                                cur < minLat ? minLat = cur : null;
                            }


                            this.zoom = this.getZoom(maxLng, minLng, maxLat, minLat);

                            var x = 0.0;
                            var y = 0.0;
                            var pathPolygon = ''
                            for (let i = 0; i < this.area.pts.length; i += 2) {
                                x = x + parseFloat(this.area.pts[i]);
                                y = y + parseFloat(this.area.pts[i + 1]);
                                pathPolygon = pathPolygon + parseFloat(this.area.pts[i]) + ',' + parseFloat(this.area.pts[i + 1]) + ';'
                            }
                            this.longitude = (x / this.area.pts.length) * 2;
                            this.latitude = (y / this.area.pts.length) * 2;

                            this.url = `http://api.map.baidu.com/staticimage/v2?ak=0MA953dkYQM4fQriWe6NaII8QpjeCCZh&center=${ this.longitude},${ this.latitude}&width=1000&height=320&zoom=${this.zoom}&paths=${pathPolygon}&pathStyles=0xff0000,5,0.9,0xffffff&bbox=500,500;500,500 `
                        }

                    }

                }

            },

        },

        methods: {

          //地图显示隐藏 事件
          cancel() {
            this.dialogVisible = false

          },

          save() {
            this.dialogVisible = false
          },

          dialogVisible2() {
            this.dialogVisible = true
          },

          //根据经纬极值计算绽放级别。
          getZoom(maxLng, minLng, maxLat, minLat) {

            this.map = new BMap.Map();

            var zoom = ["50", "100", "200", "500", "1000", "2000", "5000", "10000", "20000", "25000", "50000", "100000", "200000", "500000", "1000000", "2000000"]//级别18到3。
            var pointA = new BMap.Point(maxLng, maxLat);  // 创建点坐标A
            var pointB = new BMap.Point(minLng, minLat);  // 创建点坐标B
            var distance = this.map.getDistance(pointA, pointB).toFixed(1);  //获取两点距离,保留小数点后两位
            for (var i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
              if (zoom[i] - distance > 0) {
                return 18 - i + 1;//之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。
              }
            }
          },

          //对话框
          handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                  done();
                })
                .catch(_ => {
                });
          },

            areaSave() {
                if (this.pts != null && this.pts.length > 0) {
                    this.area.pts = this.pts
                } else {
                    this.area.pts = []
                }
                if (this.areaGroups.length > 0) {
                    this.area.group = this.areaGroups[this.areaGroups.length - 1]
                }
                this.area.disabled = this.disabled
                this.area.hidden = this.hidden

                this.area.disabled = this.disabled
                this.area.hidden = this.hidden

                if (this.area.type == 1 || this.area.type == 2) {
                    let s = this.area.value;
                    if (isNaN(s)) {
                        this.$message.error("输入正确的可停车辆数或最大限速")
                    } else {
                        var d = this.area
                        saveArea(d).then(res => {
                            if (res != null && res.code == 200) {
                                this.$message.success("保存成功！！！")
                                //跳转页面
                                this.$router.push('/area')
                            } else {
                                this.$message.error("保存失败！！！")
                            }
                        })
                    }
                } else {
                    var d1 = this.area
                    saveArea(d1).then(res => {
                        if (res != null && res.code == 200) {
                            this.$message.success("保存成功！！！")
                            //跳转页面
                            this.$router.push('/area')
                        } else {
                            this.$message.error("保存失败！！！")
                        }
                    })
                }

            },

            /*获取分组信息*/
            getAreaGroupsInfo() {
                getGroupTree({}).then(res => {
                    this.groups = res.data.children
                })
            },

            /*重置数据*/
            reset() {
                Object.assign(this.$data, this.$options.data())
                for (var i = 0; i < this.overlays.length; i++) {
                    this.map.removeOverlay(this.overlays[i]);
                }
                this.overlays.length = 0;
                this.pts = []
                this.getAreaGroupsInfo()
            },

            /*  百度地图*/
            //清除绘制区域
            clearAll() {
              alert("清除之后无法恢复，请谨慎操作！")
                for (var i = 0; i < this.overlays.length; i++) {
                    this.map.removeOverlay(this.overlays[i]);
                }
                this.overlays.length = 0;
                this.pts = []
            },

            //获取覆盖物
            overlaycomplete(e) {

                this.overlays.push(e.overlay);
                if (this.overlays.length == 0) {
                    this.pts = []
                }

                else if (this.overlays.length > 1) {

                    alert("只能绘制一个区域！！！")
                    for (var i = 0; i < this.overlays.length; i++) {
                        this.map.removeOverlay(this.overlays[i]);
                    }
                    this.overlays.length = 0;
                    this.pts = []
                } else {
                    var path = e.overlay.getPath(); //Array<Point> 返回多边型的点数组
                    if (path != null) {
                        if (this.overlays[0].__proto__.PQ == 'Polygon') {
                            this.area.shape = 1
                            for (var j = 0; j < path.length; j++) {
                                this.pts.push(path[j].lng)
                                this.pts.push(path[j].lat)
                            }
                        } else if (this.overlays[0].__proto__.PQ == 'Circle') {
                            this.area.shape = 3
                            this.pts.push(this.overlays[0].point.lng)
                            this.pts.push(this.overlays[0].point.lat)
                            this.area.radius = parseInt(this.overlays[0].xa)

                            for (let i = 0; i < this.overlays[0].ha.length; i++) {
                                this.pts.push(this.overlays[0].ha[i].lng)
                                this.pts.push(this.overlays[0].ha[i].lat)
                            }
                        }
                    }
                }
            },

        },

        created() {

        },

        mounted() {

            if (this.$route.query.area != null) {
                this.area = this.$route.query.area
                this.areaGroups = this.area.group
            }
            this.getAreaGroupsInfo()


            //百度地图
            this.map = new BMap.Map("dbmap", {
                enableMapClick: false // 禁止底图点击事件
            });
            //全国
            //this.map.centerAndZoom(new BMap.Point(103.388611,35.563611), 5);
            //合肥市
            this.map.centerAndZoom(new BMap.Point(117.246258, 31.837809), 17);
            this.map.enableScrollWheelZoom();
            this.map.enableMapClick = false;

            //开启定位
            this.map.addControl(new BMap.GeolocationControl());

            //实例化鼠标绘制工具
            this.drawingManager = new BMapLib.DrawingManager(this.map, {
                isOpen: false, //是否开启绘制模式
                enableDrawingTool: true, //是否显示工具栏
                drawingToolOptions: {
                    anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                    offset: new BMap.Size(5, 5), //偏离值
                    drawingModes: [ // 可见的操作选项
                        // BMAP_DRAWING_MARKER,
                        //圆形
                        BMAP_DRAWING_CIRCLE,
                        // BMAP_DRAWING_POLYLINE,
                        //多边形
                        BMAP_DRAWING_POLYGON,
                        //矩形
                        BMAP_DRAWING_RECTANGLE
                    ]
                },

            });

            // document.getElementsByTagName("svg")[0].innerHTML = "<path stroke-linejoin=\"round\" stroke-linecap=\"round\" fill-rule=\"evenodd\" stroke=\"#3a6bdb\" stroke-width=\"5\" stroke-dasharray=\"none\" fill=\"#fff\" stroke-opacity=\"0.65\" fill-opacity=\"0.65\" style=\"cursor: pointer; user-select: none;\" d=\"M 592 -154 L 559 -151 526 -144 496 -131 467 -114 442 -92 420 -67 403 -39 390 -8 383 24 380 57 383 90 390 122 403 153 421 181 442 206 467 228 496 245 526 258 559 265 592 268 625 265 658 258 688 245 717 228 742 206 763 181 781 153 794 122 801 90 804 57 801 24 794 -8 781 -39 764 -67 742 -92 717 -114 688 -131 658 -144 625 -151 592 -154\"></path>"

            //添加鼠标绘制工具监听事件，用于获取绘制结果
            this.drawingManager.addEventListener('overlaycomplete', this.overlaycomplete);

            this.getAreaGroupsInfo()

        },

    }

</script>

<style scoped>

    #dbmap {
        margin: 0 auto;
        width: 100%;
        height: 500px;
    }

</style>
